<template>
    <div class="login">
        <el-form 
            :model="form"
            :rules="rules"
            ref="eForm"
        >
            <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button-group class="login-btns">
                    <el-button
                        type="primary" 
                        :loading="loading"
                        @click="login"
                    >登录</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-button-group>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
    import { ref, reactive } from 'vue'
    import { useRouter } from 'vue-router'
    
    const eForm = ref(null)
    const form = reactive({
        username: '',
        password: ''
    })
    const rules = reactive({
        username: [{
            required: true, 
            message: '请输入用户名', 
            trigger: 'blur'
        }],
        password: [{
            required: true, 
            message: '请输入密码', 
            trigger: 'blur'
        }]
    })
    const loading = ref(false)
    const router = useRouter()
    
    function login() {
        eForm.value.validate((valid) => {
            if (!valid) {
                return false
            }
            
            const token = `${form.username}-${form.password}`
            localStorage.setItem('token', token)
            loading.value = true
            setTimeout(() => {
                loading.value = false
                router.push('/home')
            }, 2000)
        })
    }
    
    function reset() {
        eForm.value.resetFields()
    }
</script>

<style lang="less">
    .login {
        position: absolute;
        top: 40%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 300px;
        
        &-btns {
            display: flex;
            margin-top: 22px;
            
            > * {
                flex: 1
            }
        }
    }
</style>